﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class DiskFactory : MonoBehaviour {
    // 用list 记录即将使用的飞碟和释放了的飞碟
    private List<Disk> used = new List<Disk>();
    private List<Disk> free = new List<Disk>();

    //从工厂中拿一个飞碟
    public GameObject GetDisk(int type) {
        GameObject disk_prefab = null;
        //找一个释放了的飞碟
        if (free.Count>0) {
            for(int i = 0; i < free.Count; i++) {
                if (free[i].type == type) {
                    disk_prefab = free[i].gameObject;
                    free.Remove(free[i]);
                    break;
                }
            }     
        }
        //通过预制生成飞碟
        type = (type>3)? 3:type;
        if(disk_prefab == null) {
            disk_prefab = Instantiate(
            Resources.Load<GameObject>("Prefabs/disk"+ (type).ToString()),
            new Vector3(0, -10f, 0), Quaternion.identity);
            disk_prefab.GetComponent<Disk>().score = type;
            disk_prefab.GetComponent<Renderer>().material.color = disk_prefab.GetComponent<Disk>().color;
        }
        //返回生成的飞碟
        used.Add(disk_prefab.GetComponent<Disk>());
        disk_prefab.SetActive(true);
        return disk_prefab;
    }

    // 释放全部飞碟
    public void FreeDisk() {
        for(int i=0; i<used.Count; i++) {
            if (used[i].gameObject.transform.position.y < -10) {
                free.Add(used[i]);
                used.Remove(used[i]);
            }
        }          
    }

    public void Reset() {
        FreeDisk();
    }
}
